/* eslint-disable no-unsafe-optional-chaining */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-use-before-define */
import DictTag from "@/components/DictTag";
import { EditOutlined, DeleteOutlined, ExclamationCircleFilled, PlusOutlined } from "@ant-design/icons";
import { ActionType, PageContainer, ProColumns } from "@ant-design/pro-components";
import {
	Button,
	Card,
	Divider,
	Flex,
	FormInstance,
	Input,
	List,
	Modal,
	Popconfirm,
	Skeleton,
	Space,
	Typography,
	message
} from "antd";
import { DataNode } from "antd/es/tree";
import React, { useEffect, useRef, useState } from "react";
import DataScope from "./components/DataScope";
import MenuForm from "./components/MenuForm";
import RoleForm, { RoleFormData } from "./components/RoleForm";
// import { DragDropContext, Droppable, useSortable } from '@dnd-kit/core';
// import { SortableContext, sortableKeyboardCoordinates } from '@dnd-kit/sortable';
// import DataScopeForm from './components/DataScope';
// import UpdateForm from './edit';
import CustomerTable from "@/components/CustomerTable";
import { getPageList, remove, save, update } from "@/services/api/module/system/role";
import { getDict } from "@/services/api/module/system/dict";
import FilterDrawer from "@/components/FilterDrawer";
import ImportExportDropdown from "@/components/ImportExportDropdown";
import { createTableColumns, pagination } from "./contents";
import { Panel, PanelGroup, PanelResizeHandle } from "react-resizable-panels";
import styles from "./style/index.module.less";
import { useEmotionCss } from "@ant-design/use-emotion-css";
import TreeTableList from "@/components/TreeTableList/TreeTableList";
import { getList } from "@/services/api/module/system/menu";
const { confirm } = Modal;
const RoleTableList: React.FC = () => {
	const formTableRef = useRef<FormInstance>();
	const [modalVisible, setModalVisible] = useState<boolean>(false);
	const [menuOpen, setMenuOpen] = useState<boolean>(false);
	const [formOpen, setFormOpen] = useState<boolean>(false);
	const [menuVisible, setMenuVisible] = useState<boolean>(false);
	const [dataScopeModalOpen, setDataScopeModalOpen] = useState<boolean>(false);
	const actionRef = useRef<ActionType>();
	const [currentRow, setCurrentRow] = useState<API.Setting.Role>();
	const [currentId, setCurrentId] = useState<number | undefined>(undefined);
	const [scopeRoleId, setScopeRoleId] = useState<number | undefined>(undefined);
	const [scopeOpen, setScopeOpen] = useState<boolean>(false);
	const [selectedRows, setSelectedRows] = useState<API.Setting.Role[]>([]);
	const [menuTree, setMenuTree] = useState<DataNode[]>();
	const [menuIds, setMenuIds] = useState<string[]>([]);
	const [statusOptions, setStatusOptions] = useState<any>([]);
	const [dataScopeEnums, setDataSCopeEnums] = useState<any>([]);
	const [authMenuOpen, setAuthMenuOpen] = useState<boolean>(false);
	const [selectIndex, setSelectIndex] = useState<number | null>(null);
	const [data, setData] = useState<any>([]);
	const [activeTabKey, setActiveTabKey] = useState<string>("dataPromission");
	useEffect(() => {
		getMenuTree();
	}, []);
	// 获取树菜单
	const getMenuTree = () => {
		getList().then((data: any) => {
			setData(data?.data);
		});
	};
	const roleClassName = useEmotionCss(({ token }) => {
		return {
			width: "100%",
			height: "40px",
			padding: "0 10px",
			borderRadius: token.borderRadiusSM,
			"&:hover": {
				background: token.colorBgTextHover,
				cursor: "pointer"
			},
			".oper": {
				display: "none"
			},
			"&:hover .oper": {
				display: "block"
			}
		};
	});
	useEffect(() => {
		getDict("sys_base_status").then(data => {
			setStatusOptions(data);
		});
		getDict("sys_data_scope").then(data => {
			setDataSCopeEnums(data);
		});
	}, []);
	const handleColumnEditor = (record: any) => {
		setFormOpen(true);
		setCurrentId(record.id);
	};
	const handleColumnRemove = (record: any) => {
		handleRemove(record?.id);
	};
	const handleColumnAuth = (record: any) => {
		setModalVisible(true);
		setCurrentId(record.id);
	};
	const handleColumnMenu = (record: any) => {
		setAuthMenuOpen(true);
		setCurrentId(record.id);
	};
	const handlePremission = (record: any) => {
		setScopeRoleId(record.id);
		setScopeOpen(true);
	};
	// 列定义
	// 列表字段
	const columns: ProColumns<API.Setting.RoleVo>[] = createTableColumns(
		statusOptions,
		handleColumnEditor,
		handleColumnRemove,
		handleColumnAuth,
		handleColumnMenu,
		handlePremission
	);

	// 删除
	const handleRemove = async (ids: number | Array<number>) => {
		return new Promise((reslove, reject) => {
			remove(ids)
				.then((res: any) => {
					message.success(res.msg);
					if (actionRef.current) {
						actionRef.current.reload();
					}
					reslove(true);
				})
				.catch(() => {
					reject(true);
				});
		});
	};
	// 删除警告提示
	const showRemoveConfirm = (ids: Array<number>, names: Array<string>) => {
		confirm({
			title: "警告",
			icon: <ExclamationCircleFilled />,
			content: `确认删除角色名称为：${names} 的角色吗?`,
			onOk() {
				return handleRemove(ids);
			},
			onCancel() {}
		});
	};
	// 保存
	const handleSave = async (values: RoleFormData) => {
		return new Promise((resolve, reject) => {
			save({ ...values } as RoleFormData)
				.then((res: any) => {
					message.success(res.msg);
					handleTableForm();
					resolve(true);
				})
				.catch(() => {
					reject(false);
				});
		});
	};
	// 編輯
	const handleUpdate = async (values: RoleFormData) => {
		return new Promise((resolve, reject) => {
			update({ ...values } as RoleFormData)
				.then((res: any) => {
					message.success(res.msg);
					handleTableForm();
					resolve(true);
				})
				.catch(() => {
					reject(false);
				});
		});
	};
	// 关闭表单刷新列表
	const handleTableForm = async () => {
		setFormOpen(false);
		setCurrentId(undefined);
		actionRef?.current?.reload();
	};
	const [searchFormValue, setSearchFormValue] = useState<any>(undefined);
	const [searchValue, setSearchValue] = useState<any>(undefined);

	const handleOnSearch = async (value: any) => {
		setSearchValue({
			userName: value
		});
		actionRef.current?.reload();
	};
	const handleFormCancel = () => {
		setFormOpen(false);
		setCurrentId(undefined);
	};
	const handleMouseEnter = (index: number) => {
		setSelectIndex(index);
	};
	const handleMouseUserLeave = () => {
		setSelectIndex(null);
	};
	const pageInfo = React.useRef({
		pageSize: 5,
		current: 1
	});
	const [dataa, setDataa] = useState([]);
	const [total, setTotal] = useState<number>(0);
	const [loading, setLoading] = useState(false);
	//数据请求
	const tableDataRequest = async () => {
		if (loading) {
			return;
		}
		setLoading(true);
		return await getPageList({ ...pageInfo.current })
			.then((data: any) => {
				setTotal(total);
				// @ts-ignore
				setDataa([...dataa, ...data?.data]);
				// setDataa([...dataa, data?.data]);
				setLoading(false);
			})
			.catch(() => {
				setLoading(false);
			});
	};
	const loadData = () => {
		// current
		const pages = {
			pageSize: 5,
			current: pageInfo.current?.current + 1
		};
		pageInfo.current = pages;
		tableDataRequest();
	};
	useEffect(() => {
		tableDataRequest();
	}, []);
	return (
		<>
			<PanelGroup direction="horizontal">
				<Panel defaultSize={20} minSize={0}>
					<Card
						styles={{
							body: {
								padding: "5px 10px"
								// overflow: "auto"
							}
						}}
						title="角色列表"
						extra={<Button type="link">创建角色</Button>}
						style={{ height: "calc(100vh - 55px - 47px - 16px)" }}
					>
						<List<API.Setting.RoleVo>
							style={{ overflow: "auto", minHeight: "100%", maxHeight: "100%", marginTop: "4px" }}
							split={false}
							header={null}
							dataSource={dataa}
							renderItem={(item, index) => (
								<List.Item key={index} style={{ width: "100%", padding: "0" }}>
									<Flex
										onMouseEnter={() => handleMouseEnter(0)}
										onMouseLeave={() => handleMouseUserLeave()}
										justify="space-between"
										align="center"
										className={roleClassName}
									>
										<Typography>{item?.roleName}</Typography>

										<div className={"oper"}>
											<Space size={5}>
												<Typography.Link>
													<EditOutlined />
												</Typography.Link>
												<Typography.Link>
													<DeleteOutlined />
												</Typography.Link>
											</Space>
										</div>
									</Flex>
								</List.Item>
							)}
						/>
						{/* {sortableProvided => (
									<ul {...sortableProvided.droppableProps} ref={sortableProvided.setNodeRef}>
										{list.map((item, index) => (
											<Sortable.Item key={item} id={item}>
												{sortableItemProvided => (
													<li
														{...sortableItemProvided.attributes}
														{...sortableItemProvided.listeners}
														ref={sortableItemProvided.setNodeRef}
													>
														{item}
													</li>
												)}
											</Sortable.Item>
										))}
										{sortableProvided.placeholder}
									</ul>
								)} */}
					</Card>
				</Panel>
				<PanelResizeHandle style={{ width: 10 }} />
				<Panel minSize={75}>
					<Card
						style={{ height: "calc(100vh - 55px - 47px - 16px)" }}
						title={"应用权限"}
						styles={{
							body: {
								padding: "10px"
							}
						}}
						activeTabKey={activeTabKey}
						accessKey="appPromission"
						onTabChange={(key: string) => {
							setActiveTabKey(key);
						}}
						tabList={[
							{
								key: "appPromission",
								label: "应用权限"
							},
							{
								key: "dataScope",
								label: "数据权限"
							}
						]}
					>
						{activeTabKey === "appPromission" && (
							<TreeTableList
								onChange={vals => {
									console.log("vals", vals);
								}}
								// size="small"
								fieldNames={{ label: "menuName", value: "id", children: "children" }}
								treeData={data}
								lastColumnMerged
								columns={[{ title: "目录" }, { title: "菜单" }, { title: "按钮" }]}
							/>
						)}
					</Card>
				</Panel>
			</PanelGroup>
		</>
	);
};

export default RoleTableList;
